package mina;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

public class MinaClient {
    private static final Logger log = Logger.getLogger(MinaClient.class.getSimpleName());

    public static void main(String[] args) throws Exception {
        // 创建客户端连接器.
        NioSocketConnector con = new NioSocketConnector(Runtime.getRuntime().availableProcessors());
        con.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(StandardCharsets.UTF_8)));
        //设置连接超时检查时间
        con.setConnectTimeoutCheckInterval(30);
        //设置处理程序
        con.setHandler(new MyIohandler());

        ConnectFuture future = con.connect(new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 8787));
        //等待连接创建完成
        future.awaitUninterruptibly();
        IoSession session = future.getSession();
        session.write("你好,当前时间为:" + Instant.now());
        TimeUnit.SECONDS.sleep(5);
        session.write("你好2,当前时间为:" + Instant.now());
        TimeUnit.SECONDS.sleep(5);
        session.write("quit");
        //等待连接断开
        session.getCloseFuture().awaitUninterruptibly();
        //释放连接
        con.dispose();
    }

    static class MyIohandler extends IoHandlerAdapter {

        @Override
        public void messageReceived(IoSession session, Object message) throws Exception {
            log.info(() -> "接受数据为:" + message);
        }

        @Override
        public void messageSent(IoSession session, Object message) throws Exception {
            log.info(() -> "发送数据为:" + message);
        }

    }
}
